using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class Door : Interactive
{
	[Header("Door")]
	public bool opened = true;
	public bool locked = false;
	public DoorID doorID;
	public DoorType doorType;
	public enum DoorType
	{
		Left = 0,
		Double = 1,
		Right = 2,
	}

	public List<TileConnection> connections = new List<TileConnection>();

	public Animator animator;

	protected override void Awake ()
	{
		base.Awake ();

		if (opened)
		{
			animator.SetTrigger("QuickOpen");
		}
		else
		{
			animator.SetTrigger("QuickClose");
		}

		foreach (TileConnection connection in connections)
		{
			connection.tile1.neighbourDoors.Add(this);
			connection.tile2.neighbourDoors.Add(this);
		}
	}

	protected override void Start ()
	{
		base.Start ();
		Init(null);
	}

	// Called in Awake by Interactive
	public override void RecalculateAreas()
	{
		selectArea.Clear();
		foreach (TileConnection connection in connections)
		{
			selectArea.Add(connection.tile1);
			selectArea.Add(connection.tile2);
		}
	}

	public void OpenDoor()
	{
		opened = !opened;
		if (opened)
		{
			animator.SetTrigger("Open");
		}
		else
		{
			animator.SetTrigger("Close");
		}
	}

	public bool IsOpen()
	{
		return opened;
	}

	public bool IsConnected(Tile _tile1, Tile _tile2)
	{
		foreach (TileConnection connection in connections)
		{
			if ((connection.tile1 == _tile1 && connection.tile2 == _tile2)
			    || connection.tile2 == _tile1 && connection.tile1 == _tile2)
			{
				return true;
			}
		}

		return false;
	}

	public override void InteractiveClicked()
	{
		Player player = InitiativeManager.Instance.current as Player;
		if (!locked || player.HasKey(doorID))
		{
			InitiativeManager.Instance.current.PerformAction(this, "OpenDoor", pathForInteraction);
			player.UseKey(doorID);
			locked = false;
		}
	}

	public override bool SetAsSelectable(List<Tile> _path)
	{
		bool b = base.SetAsSelectable(_path);
		fxActive.GetComponent<DoorFX>().SetLocked(locked);

		return b;
	}

	[System.Serializable]
	public class TileConnection
	{
		public Tile tile1;
		public Tile tile2;

		public TileConnection(Tile _tile1, Tile _tile2)
		{
			tile1 = _tile1;
			tile2 = _tile2;
		}
	}
}
